#!/usr/bin/env node

import inquirer from "inquirer";
import chalk from "chalk";
import figlet from "figlet";
import shell from "shelljs";
import dayjs from "dayjs";
import customParseFormat from "dayjs/plugin/customParseFormat.js";

dayjs.extend(customParseFormat);

const init = () => {
  console.log(
    chalk.green(
      figlet.textSync("hello tcc", {
        font: "Ghost",
        horizontalLayout: "default",
        verticalLayout: "default",
      })
    )
  );
};

// 问卷
const askQuestions = () => {
  const questions = [{
      type: "list",
      name: "type",
      message: "选择功能？",
      default: "固定时间关机",
      choices: [
        "固定时间关机",
        "固定时长关机",
        "立即关机",
        "取消定时关机",
        "退出",
      ],
    },
    {
      name: "time",
      type: "input",
      message: "关机时间？（如：12:20）",
      when: (data) => data.type === "固定时间关机",
      validate: (value) => {
        if (!dayjs(value, "HH:mm", true).isValid()) {
          return new Error("时间格式错误");
        }

        return true;
      },
    },
    {
      name: "long",
      type: "input",
      message: "多久后关机? （如：2h,20m,100s）",
      when: (data) => data.type === "固定时长关机",
      validate: (value) => {
        if (!/(h|m|s)$/.test(value)) {
          return new Error("时长格式错误");
        }

        return true;
      },
    },
  ];

  return inquirer.prompt(questions);
};

const success = (message) => {
  console.log(chalk.white.bgRed.bold(message));
};

// 固定时间关机
const timeClose = (time) => {
  success("时间：" + time);
  const inputDate = dayjs().format("YYYY-MM-DD");
  const inputTime = +new Date(`${inputDate} ${time}:00`);
  const nowTime = +new Date();

  if (inputTime > nowTime) {
    const result = Math.ceil((inputTime - nowTime) / 1000);

    shell.exec(`shutdown -s -t ${result}`);
  } else {
    console.log(chalk.white.bgRed.bold("输入时间不能小于当前时间"));
  }
}

// 固定时长关机
const timeLengthClose = long => {
  let result;
  if (/h$/.test(long)) {
    // 小时
    result = Number(long.replace("h", "").trim()) * 60 * 60;
  }

  if (/m$/.test(long)) {
    // 分钟
    result = Number(long.replace("m", "").trim()) * 60;
  }

  if (/s$/.test(long)) {
    // 分钟
    result = Number(long.replace("s", "").trim());
  }

  success("时长：" + long);

  shell.exec(`shutdown -s -t ${result}`);
}

// 主程序
const run = async () => {
  let arg = process.argv[2]

  // 快捷方式，启动参数
  // -1 取消定时关机
  // 0  立即关机
  // 时间格式，如：HH:mm:ss 固定时间关机
  // 时长格式，如：12h、12m、12s 固定时长关机
  if (arg === '-1') {
    // 取消关机
    shell.exec(`shutdown -a`);
    return

  } else if (arg === '0') {
    shell.exec(`shutdown -s -t 0`);
    return

  } else if (arg && /^(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d$/.test(arg + ':00')) {
    timeClose(arg)
    console.log('24小时');
    return
  } else if (/h$/.test(arg) || /m$/.test(arg) || /s$/.test(arg)) {
    timeLengthClose(arg)
    return

  }

  init();

  // ask questions
  const answers = await askQuestions();
  const {
    type,
    time,
    long
  } = answers;

  success("所选类型：" + type);

  if (type === "固定时间关机") {
    timeClose(time)
  } else if (type === "固定时长关机") {
    timeLengthClose(long)
  } else if (type === "立即关机") {
    shell.exec(`shutdown -s -t 0`);
  } else if (type === "取消定时关机") {
    shell.exec(`shutdown -a`);
  } else {
    shell.exit();
  }
};

run();